package com.marketingexpert.controller.marketingmgnt.activityrecomment;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.marketingexpert.config.SystemErrorCode;
import com.marketingexpert.exception.MarketingExpertException;
import com.marketingexpert.service.marketingmgnt.MarketingService;
import com.marketingexpert.util.Resources;
import com.marketingexpert.util.WebUtils;
import com.taobao.api.domain.Coupon;

public class QuerySingleCoupon implements Controller {

	private static Logger logger = Logger.getLogger(QuerySingleCoupon.class);
	
	private MarketingService marketingService;
	
	private String success;
	
	private SystemErrorCode systemErrorCode;
	
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		
		String couponId = request.getParameter("couponId");
		
		String sessionKey = (String) request.getSession().getAttribute("taobaoSessionKey");
		
		if(couponId == null) {
			request.setAttribute("parameterNull", Resources.getString("PublishActivity.parameterNull"));
			request.getSession().getServletContext().getRequestDispatcher("/marketingmgnt/coupon/getActivities.do").forward(request, response);
			return null;
		}
		
		try {
			List<Coupon> coupon = getMarketingService().getExistCoupon(couponId, 0L, sessionKey);
			return new ModelAndView(getSuccess(), "coupon" ,coupon.get(0));			
		} catch(MarketingExpertException e) {
			if(e.getErrCode().equals(systemErrorCode.getInvalidSession()) || e.getErrCode().equals(systemErrorCode.getTaobaoExpiredSession())) {
				request.getSession().removeAttribute("taobaoSessionKey");
				request.getSession().removeAttribute("parentUserId");
				request.getSession().setAttribute("sessionExpired", Resources.getString("InvalidSession"));
				response.sendRedirect(WebUtils.getBasepath(request) + "/pages/sessionExpiredTip.jsp");
				return null;
			}
			request.setAttribute("QueryCouponFailed", Resources.getString("QuerySingleCoupon.querySingleCouponFailed"));
			request.getSession().getServletContext().getRequestDispatcher("/marketingmgnt/coupon/getExistCoupon.do").forward(request, response);
			return null;
		}
	}

	public MarketingService getMarketingService() {
		return marketingService;
	}

	public void setMarketingService(MarketingService marketingService) {
		this.marketingService = marketingService;
	}

	public String getSuccess() {
		return success;
	}

	public void setSuccess(String success) {
		this.success = success;
	}

	public SystemErrorCode getSystemErrorCode() {
		return systemErrorCode;
	}

	public void setSystemErrorCode(SystemErrorCode systemErrorCode) {
		this.systemErrorCode = systemErrorCode;
	}

}
